﻿using System;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Nop.Core;
using Nop.Core.Domain.Orders;
using Nop.Plugin.Widgets.BsLiveChat.Models;
using Nop.Services.Catalog;
using Nop.Services.Configuration;
using Nop.Services.Localization;
using Nop.Services.Logging;
using Nop.Services.Orders;
using Nop.Services.Stores;
using Nop.Web.Framework.Controllers;

namespace Nop.Plugin.Widgets.BsLiveChat.Controllers
{
    public class WidgetsBsLiveChatController : BasePluginController
    {
        private readonly IWorkContext _workContext;
        private readonly IStoreContext _storeContext;
        private readonly IStoreService _storeService;
        private readonly ISettingService _settingService;
        private readonly IOrderService _orderService;
        private readonly ILogger _logger;
        private readonly ICategoryService _categoryService;
        private readonly IProductAttributeParser _productAttributeParser;
        private readonly ILocalizationService _localizationService;

        public WidgetsBsLiveChatController(IWorkContext workContext,
            IStoreContext storeContext, 
            IStoreService storeService,
            ISettingService settingService, 
            IOrderService orderService, 
            ILogger logger, 
            ICategoryService categoryService,
            IProductAttributeParser productAttributeParser,
            ILocalizationService localizationService)
        {
            this._workContext = workContext;
            this._storeContext = storeContext;
            this._storeService = storeService;
            this._settingService = settingService;
            this._orderService = orderService;
            this._logger = logger;
            this._categoryService = categoryService;
            this._productAttributeParser = productAttributeParser;
            this._localizationService = localizationService;
        }

        [AdminAuthorize]
        [ChildActionOnly]
        public ActionResult Configure()
        {
            //load settings for a chosen store scope
            var storeScope = this.GetActiveStoreScopeConfiguration(_storeService, _workContext);
            var BsLiveChatSettings = _settingService.LoadSetting<BsLiveChatSettings>(storeScope);
            var model = new ConfigurationModel();
           
            model.TrackingScript = BsLiveChatSettings.TrackingScript;
            

            model.ActiveStoreScopeConfiguration = storeScope;
            if (storeScope > 0)
            {
              
                model.TrackingScript_OverrideForStore = _settingService.SettingExists(BsLiveChatSettings,
                    x => x.TrackingScript, storeScope);
            }
            return View("~/Plugins/Widgets.BsLiveChat/Views/WidgetsBsLiveChat/Configure.cshtml", model);
        }

        [HttpPost]
        [AdminAuthorize]
        [ChildActionOnly]
        public ActionResult Configure(ConfigurationModel model)
        {
            //load settings for a chosen store scope
            var storeScope = this.GetActiveStoreScopeConfiguration(_storeService, _workContext);
            var BsLiveChatSettings = _settingService.LoadSetting<BsLiveChatSettings>(storeScope);
            BsLiveChatSettings.TrackingScript = model.TrackingScript;
            
            /* We do not clear cache after each setting update.
             * This behavior can increase performance because cached settings will not be cleared 
             * and loaded from database after each update */
           
            
            if (model.TrackingScript_OverrideForStore || storeScope == 0)
                _settingService.SaveSetting(BsLiveChatSettings, x => x.TrackingScript, storeScope, false);
            else if (storeScope > 0)
                _settingService.DeleteSetting(BsLiveChatSettings, x => x.TrackingScript, storeScope);
            
                
            //now clear settings cache
            _settingService.ClearCache();

            SuccessNotification(_localizationService.GetResource("Admin.Plugins.Saved"));

            return Configure();
        }

        [ChildActionOnly]
        public ActionResult PublicInfo(string widgetZone, object additionalData = null)
        {
            string globalScript = "";

            try
            {
                

               
               
                    globalScript += GetTrackingScript();
                
            }
            catch (Exception ex)
            {
                _logger.InsertLog(Core.Domain.Logging.LogLevel.Error, "Error creating scripts for Bs Live Chat", ex.ToString());
            }
            return Content(globalScript);
        }

       
        
        
        private string GetTrackingScript()
        {
            var BsLiveChatSettings = _settingService.LoadSetting<BsLiveChatSettings>(_storeContext.CurrentStore.Id);
            var analyticsTrackingScript = BsLiveChatSettings.TrackingScript + "\n";
           
            return analyticsTrackingScript;
        }
        
        
        
    }
}